<?php


namespace NanQi\Hope\Controller;


use Hyperf\Contract\ConfigInterface;
use Hyperf\Crontab\PipeMessage;
use Hyperf\HttpServer\Annotation\GetMapping;
use NanQi\Hope\Base\BaseController;
use Hyperf\HttpServer\Annotation\Controller;
use NanQi\Hope\Crontab\Crontab;
use NanQi\Hope\Crontab\CrontabExecutor;

/**
 * @Controller()
 * Class HealthCheckController
 * @package NanQi\Hope\Controller
 */
class CrontabController extends BaseController
{
    /**
     * @GetMapping(path="/stop_crontab")
     */
    public function stop_crontab()
    {
        /** @var ConfigInterface $config */
        $config = di(ConfigInterface::class);

        //启动删除标志位
        $this->getRedisBusiness()->del('stop:crontab:' . $config->get('app_name'));

        if ($this->getServer()->getWorkerId() == 0) {
            $instance = di(CrontabExecutor::class);
            $instance->stop();
        } else {
            $this->getServer()->sendMessage(new PipeMessage(
                'callback',
                [CrontabExecutor::class, 'stop'],
                new Crontab()
            ), 0);
        }

        $redis = $this->getRedisBusiness();
        while (1) {
            $stop = $redis->get('stop:crontab:' . $config->get('app_name'));
            if ($stop == 1) {
                //删除标志位
                $this->getRedisBusiness()->del('stop:crontab:' . $config->get('app_name'));
                break;
            } else {
                sleep(1);
            }
        }

        $this->getLog()->debug('stop end');
        $this->getServer()->shutdown();
    }
}